<?php
declare (strict_types = 1);

namespace app\model;

use app\common\model\CacheRefreshHandler;
use app\common\service\redis\PoolRedis;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * @mixin \think\Model
 */
class AdminStaffIcCard extends Model
{
    //
    const BLUE_TOOTH = 1; // 蓝牙开锁
    const TEMP_PWD = 2; // 临时密码
    const SUPER_SIM = 3; // 超级SIM卡
    const IC_CARD = 4; // IC卡
    protected $autoWriteTimestamp = true;

    public function school(): BelongsTo {
        return $this->belongsTo(AdminSchool::class, 'school_id')
            ->where('is_delete', 0)->bind([
            'school_name' => 'name'
        ]);
    }

    public function staff(): BelongsTo {
        return $this->belongsTo(AdminStaff::class, 'staff_id');
    }

    /*楼栋信息*/
    public function dormitory(): BelongsTo {
        return $this->belongsTo(AdminDormitory::class, 'dormitory_id')
            ->where('is_delete', 0)->bind([
            'dormitory_name' => 'name'
        ]);
    }

    /*宿舍信息*/
    public function student(): BelongsTo {
        return $this->belongsTo(AdminStudentDormitory::class, 'student_dormitory_id')
            ->where('is_delete', 0)->bind([
            'student_dormitory_name' => 'name'
        ]);
    }

    public function getActivateTimeAttr($value,$data)
    {
        if ($data['activate_time'] == 0) {
            return '';
        }
        return date('Y-m-d H:i:s', $data['activate_time']);
    }

    public function getSimActivateTimeAttr($value,$data)
    {
        if ($data['sim_activate_time'] == 0) {
            return '';
        }
        return date('Y-m-d H:i:s', $data['sim_activate_time']);
    }

    public function getLockPermissionArrAttr($value, $data)
    {
        return explode(",", $data['lock_permission']);
    }

    public static function onAfterWrite($model)
    {
        // 软删除后处理
        if ($model->getAttr('is_delete') == 1) {
            // 宿舍楼学生数量调整
            if ($model->getAttr('type') == AdminStaff::STUDENT) {
                $exits = self::where('dormitory_id', $model->getAttr('dormitory_id'))
                    ->where('is_delete', 0)->findOrEmpty();
                if ($exits->isEmpty()) {
                    $redis = PoolRedis::instance();
                    $redis->hIncrBy(AdminDormitory::DORMITORY_COUNT_CACHE_KEY."user_count_".$model->getAttr('dormitory_id'), "value", -1);
                }
            }
            // 删除用户在该宿舍的编号
            CacheRefreshHandler::staffNumber($model->getAttr('staff_id'), $model->getAttr('school_id'), $model->getAttr('student_dormitory_id'), 'del');
        }
    }

    // 批量保存宿舍楼
    public static function batchInsert($staff_id, $stu_dor_permission = [], $ic_card = '')
    {
        $stu_dor_id = array_keys($stu_dor_permission);
        $insert = $old_stu_dor_id = [];
        $query = AdminStudentDormitory::alias('sd')
            ->join('admin_dormitory ad', 'sd.dormitory_id=ad.id')
            ->where('ad.is_delete', 0)
            ->where('sd.is_delete', 0)
            ->where('sd.id', 'in', $stu_dor_id)
            ->field('sd.school_id,sd.dormitory_id,sd.id');
        $stu_dor_list = $query->select()->toArray();
        foreach ($stu_dor_list as $item) {
            array_push($insert, [
                'school_id' => $item['school_id'],
                'dormitory_id' => $item['dormitory_id'],
                'student_dormitory_id' => $item['id'],
                'staff_id' => $staff_id,
                'ic_card' => $ic_card,
                'lock_permission' => implode(',', $stu_dor_permission[$item['id']])
            ]);
        }
        if ($insert) {
            $model = new AdminStaffIcCard();
            $model->saveAll($insert);
        }
    }
}
